package main

import (
	"errors"
	"fmt"
	"os"
)

type studen struct {
	StuAge int
}

// 一种方法
func (stu *studen) setAge(age interface{}) error {
	switch age.(type) {
	case int:
		stu.StuAge = age.(int)
	case string:
		return errors.New("字符串类型")
	default:
		//设置默认类型
		stu.StuAge = 3
		//返回错误
		return errors.New("不是这种类型")
	}
	if stu.StuAge > 200 || stu.StuAge < 0 {
		stu.StuAge = 3
		return fmt.Errorf("年龄大小异常,值为%d", age)
	}
	return nil

}

// 另一种表现形式
func setAge2(stu *studen, age interface{}) error {
	switch age.(type) {
	case int:
		stu.StuAge = age.(int)
	case string:
		return errors.New("字符串类型")
	default:
		//设置默认类型
		stu.StuAge = 3
		//返回错误
		return errors.New("不是这种类型")
	}
	if stu.StuAge > 200 || stu.StuAge < 0 {
		stu.StuAge = 3
		return fmt.Errorf("年龄大小异常,值为%d", age)
	}
	return nil

}

func main() {
	file, err2 := os.Open("aaa.txt")
	//要有人处理,不然就会爆panic
	//file, _ := os.Open("aaa.txt")
	if err2 != nil {
		fmt.Println(err2)
		return
	}
	fmt.Println(file.Name())
	var xiaoMing studen
	var err error
	//这里同样效果
	//err = xiaoMing.setAge("haha")
	err = setAge2(&xiaoMing, file)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(xiaoMing.StuAge)
	}
	err = xiaoMing.setAge(-1)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(xiaoMing.StuAge)
	}
	fmt.Printf("%T\n", err) //*errors.errorString
	err = xiaoMing.setAge(202)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(xiaoMing.StuAge)
	}
	err = xiaoMing.setAge(20)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(xiaoMing.StuAge)
	}
}
